package ar.com.ctrln.view.dashboard.calendar;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.EventQueue;
import org.zkoss.zk.ui.event.EventQueues;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import ar.com.ctrln.control.calendar.ConsultarTemaEvento;
import ar.com.ctrln.persistence.model.evento.EventoCalendario;
import ar.com.ctrln.persistence.model.evento.EventoReunion;
import ar.com.ctrln.persistence.model.evento.TemaEvento;
import ar.com.ctrln.persistence.model.factibilidad.FactibilidadCliente;
import ar.com.ctrln.persistence.model.factibilidad.TemaFactibilidad;
import ar.com.ctrln.persistence.model.factura.Factura;
import ar.com.ctrln.view.ui.comportamientoVentana.AbstractMinimizarVentana;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class ConsultarTemasEventosController extends AbstractMinimizarVentana {

	private static final long serialVersionUID = 504153307159191128L;

	@WireVariable
	private ConsultarTemaEvento consultarTemaEvento;

	@Wire
	private Window wConsultarTemaEvento;

	@Wire
	private Listbox lbTemas;

	@Wire("#txtFilter")
	private Textbox txtFilter;

	@Wire
	private Label footer_label;

	@Wire
	private Button btnVerEvento;

	private ListModelList<TemaEvento> modelo;

	private static TemaEvento seleccion;

	@SuppressWarnings("rawtypes")
	private EventQueue actualizarTemas;

	Connection con;

	@SuppressWarnings("unchecked")
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);

		actualizarTemas = EventQueues.lookup("actualizarTemas",
				EventQueues.DESKTOP, true);
		actualizarTemas.subscribe(new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {
				modelo.clear();
				modelo.addAll(consultarTemaEvento.listarEventos());
				lbTemas.setModel(modelo);
			}
		});

		modelo = new ListModelList<TemaEvento>();

		modelo.addAll(consultarTemaEvento.listarEventos());

		lbTemas.setModel(modelo);

	}

	@Listen("onClick = #btnVerEvento")
	public void verDetalle() {
		if (null == lbTemas.getSelectedItem()) {
			Clients.showNotification("Seleccione un Tema", lbTemas);
		} else {
			seleccion = lbTemas.getSelectedItem().getValue();
			wConsultarTemaEvento.setAttribute("tema", seleccion);
			Executions.createComponents(
					"/zul/administracion/eventos/detalleTema.zul",
					wConsultarTemaEvento, null);
		}

	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Listen("onChanging = #txtFilter")
	public void getFilter(Event event) {
		((Textbox) event.getTarget())
				.setValue(((org.zkoss.zk.ui.event.InputEvent) event).getValue());

		ListModelList model = new ListModelList(getFilterBy(
				txtFilter.getValue(), modelo.getInnerList()));

		model.setMultiple(true);

		lbTemas.setModel(model);

		lbTemas.setMultiple(true);

		lbTemas.setCheckmark(true);
		if (lbTemas.getItemCount() > 0) {
			footer_label.setValue("");
			footer_label.setValue("Un total de " + lbTemas.getItemCount()
					+ " Tipos de Servicio");
		} else {
			footer_label.setValue("Ningun Resultado...");
			footer_label.setValue("");
		}

		((Textbox) event.getTarget()).setFocus(true);
	}

	public static List<TemaEvento> getFilterBy(String condicion,
			Collection<TemaEvento> servicios) {
		List<TemaEvento> data = new ArrayList<TemaEvento>();
		for (Iterator<TemaEvento> i = servicios.iterator(); i.hasNext();) {
			TemaEvento tmp = i.next();
			if (tmp.getNombre().toLowerCase()
					.indexOf(condicion.trim().toLowerCase()) >= 0
					|| tmp.getEstado().toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0
					|| tmp.getObservacion().toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0) {
				data.add(tmp);
			}
		}
		return data;
	}

	@Listen("onClick = #btnImprimir")
	public void imprimirTema() throws SQLException {
		if (lbTemas.getSelectedItem() != null) {

			TemaFactibilidad t = lbTemas.getSelectedItem().getValue();
			FactibilidadCliente f = (FactibilidadCliente) t.getFactibilidad();

			SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");

			try {
				Class.forName("com.mysql.jdbc.Driver");
				con = DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/ctrln", "root", "root");
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}

			String path = this.getPage().getDesktop().getWebApp()
					.getRealPath("/resources/reportes/FactibilidadEvento.jrxml");
			String camino = path.replaceAll("\\\\", "/");

			try {
				Map param = new HashMap();
				param.put("idFact", (int) f.getId());

				JasperReport jasperReport = JasperCompileManager
						.compileReport(camino);
				JasperPrint jasperPrint = JasperFillManager.fillReport(
						jasperReport, param, con);
				JasperViewer.viewReport(jasperPrint, false);
				con.close();
			} catch (JRException e) {
				e.printStackTrace();
			}

		} else {
			Clients.showNotification("Seleccione un Tema", lbTemas);
		}
	}

}
